// 走迷宫
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int m, n;
int g[N][N]; // 存放 地图
int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // 四个方向
bool vis[N][N];
queue<PII> q;

int bfs() {
    int ans = 0;
    while (true) {
        int len = q.size();
        for (int k = 1; k <= len; k++) {
            PII top = q.front(); q.pop();
            if (top.first == n - 1 && top.second == m - 1) return ans;
            for (int i = 0; i < 4; i++) {
                int nx = top.first + d[i][0], ny = top.second + d[i][1];
                if (!vis[nx][ny] && g[nx][ny] == 0 && nx >= 0 && nx <= n - 1 && ny >= 0 && ny <= m - 1) {
                    vis[nx][ny] = true;
                    q.push(PII(nx, ny));
                }
            }
            
        }
        ans++;
    }
    return ans;
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) 
            cin >> g[i][j];
    vis[0][0] = true;
    q.push(PII(0, 0));
    cout << bfs() << endl;
    return 0;
}